const { Controller } = require('egg')
const fs = require('fs')

class WatchdogController extends Controller {
    static TABLE_GOOGDS = 'watchdog_goods'
    static TABLE_HOME = 'watchdog_home'
    static TABLE_MP_LOG = 'watchdog_mp_log'
    static TABLE_USER = 'watchdog_user'
    static REDIS_KEY_ACCESS_TOKEN = 'watchdog_mp_access_token'

    async mpLog({type, value}) {
        return await this.app.mysql.insert('watchdog_mp_log', {
            type,
            value,
            create_time: new Date().getTime(),
            ip: this.ctx.state.clientIp,
        })
    }
    async wxLogin() {
        const { jscode } = this.ctx.query
        const { appid, secret } = this.app.config.watchdog_mp
        const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${jscode}&grant_type=authorization_code`
        const requestRes = await axios.get(url)

        // console.log('requestRes', requestRes.data)
        const { openid } = requestRes.data
        
        const getUser = await this.app.mysql.get('watchdog_user', {
            openid
        })

        let insertUser = null
        let updateUser = null
        if (!getUser) {
            insertUser = await this.app.mysql.insert('watchdog_user', {
                openid,
                create_time: new Date().getTime(),
                last_login_time: new Date().getTime()
            })
        } else {
            updateUser = await this.app.mysql.update('watchdog_user', {
                last_login_time: new Date().getTime()
            }, {
                where: {id: getUser.id}
            })
        }

        this.mpLog({ type: 'login', value: JSON.stringify({openid}) })
        this.ctx.body = {
            code: 200,
            msg: 'ok',
            data: {
                getUser,
                insertUser,
                updateUser,
                openid
            }
        }
    }

    async addHome() {
        const { openid, name, addr = '', comment = '' } = this.ctx.request.body
        if (!name) {
            this.ctx.body = {
                code: 500,
                msg: '请输入门口名',
                data: {}
            }
            return
        }

        const insertRes = await this.app.mysql.insert(WatchdogController.TABLE_HOME, {
            create_user: this.ctx.currentUser.id,
            name,
            addr,
            comment,
            create_time: new Date().getTime()
        })

        this.ctx.body = {
            code: 200,
            msg: 'ok',
            data: {
                insertRes
            }
        }
    }

    async delHome() {
        const { openid, id } = this.ctx.request.body
        if (!id) {
            this.ctx.body = {
                code: 500,
                msg: '请指定门口 id',
                data: {}
            }
            return
        }

        const updateRes = await this.app.mysql.update(WatchdogController.TABLE_HOME, {
            id,
            update_time: new Date().getTime(),
            valid: 0,
        })

        this.ctx.body = {
            code: 200,
            msg: 'ok',
            data: {
                updateRes
            }
        }
    }

    async getMyHomes() {
        const { openid } = this.ctx.request.body
        const res = await this.app.mysql.select(WatchdogController.TABLE_HOME, {
            where: {
                create_user: this.ctx.currentUser.id,
                valid: 1
            },
            orders: [['update_time', 'DESC'], ['create_time', 'DESC']]
        })

        this.ctx.body = {
            code: 200,
            msg: 'ok',
            data: res
        }
    }

    async getMpAccessToken() {
        let at = await this.app.redis.get(WatchdogController.REDIS_KEY_ACCESS_TOKEN)
        if (!at) {
            const { appid, secret } = this.app.config.watchdog_mp
            const atRes = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`)
            const { access_token } = atRes.data
            await this.app.redis.set(WatchdogController.REDIS_KEY_ACCESS_TOKEN, access_token, 'EX', 7000)
            at = access_token
        }
        return at
    }
    
    async getHomeQr() {
        const { home_id } = this.ctx.request.query
        if (code === null) {
            this.ctx.body = {
                code: 500,
                msg: '缺少参数 code',
                data: {}
            }
            return
        }
        const genCodeUrl = `https://api.weixin.qq.com/wxa/getwxacode?access_token=${await this.getMpAccessToken()}`
        
        const genCodeRes = await axios.post(genCodeUrl, {
            path: `/pages/home/home?home_id=${home_id}`,
            env_version: 'release', // release
            width: 160
        }, {
            responseType: 'arraybuffer'
        })

        this.ctx.body = {
            code: 200,
            msg: 'ok',
            data: genCodeRes.data
        }
    }

    async addGood() {
        const { openid, title, number, home_id, type } = this.ctx.request.body
        if (!title) {
            this.ctx.body = {
                code: 500,
                msg: '缺少参数：title',
                data: {}
            }
            return
        }
        if (!number) {
            this.ctx.body = {
                code: 500,
                msg: '缺少参数：number',
                data: {}
            }
            return
        }
        if (!home_id) {
            this.ctx.body = {
                code: 500,
                msg: '缺少参数：home_id',
                data: {}
            }
            return
        }
        if (!type) {
            this.ctx.body = {
                code: 500,
                msg: '缺少参数：type',
                data: {}
            }
            return
        }

        const insertRes = await this.app.mysql.insert(WatchdogController.TABLE_GOOGDS, {
            title,
            number,
            home_id,
            create_user: this.ctx.currentUser.id,
            type,
            create_time: new Date().getTime(),
        })

        this.ctx.body = {
            code: 200,
            msg: 'ok',
            data: {
                insertRes
            }
        }
    }

    async getGoods() {
        const { openid, home_id } = this.ctx.request.query
    }
}

module.exports = WatchdogController
